"""
报告生成器模块
用于生成数据报告
"""

import time
import logging
from typing import Dict, List, Any
from datetime import datetime

from .data_processor import DataProcessor, format_timestamp, calculate_statistics

logger = logging.getLogger(__name__)

class ReportGenerator:
    """报告生成器，用于生成数据报告"""
    
    def __init__(self, data_processor: DataProcessor):
        """
        初始化报告生成器
        
        Args:
            data_processor: 数据处理器实例
        """
        self.data_processor = data_processor
    
    def generate_summary_report(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        生成摘要报告
        
        Args:
            items: 项目列表
            
        Returns:
            摘要报告
        """
        if not items:
            return {"count": 0, "message": "No data available"}
        
        # 计算基本统计信息
        count = len(items)
        
        # 按类型分组
        grouped_by_type = self.data_processor.group_items(items, "type")
        type_counts = {k: len(v) for k, v in grouped_by_type.items()}
        
        # 计算时间范围
        timestamps = [item.get("created_at", 0) for item in items if "created_at" in item]
        time_range = {
            "min": format_timestamp(min(timestamps)) if timestamps else None,
            "max": format_timestamp(max(timestamps)) if timestamps else None,
        }
        
        return {
            "generated_at": format_timestamp(time.time()),
            "count": count,
            "type_distribution": type_counts,
            "time_range": time_range
        }
    
    def generate_detailed_report(self, items: List[Dict[str, Any]], group_by: str) -> Dict[str, Any]:
        """
        生成详细报告
        
        Args:
            items: 项目列表
            group_by: 分组键
            
        Returns:
            详细报告
        """
        # 基本摘要
        summary = self.generate_summary_report(items)
        
        # 按指定键分组
        grouped_items = self.data_processor.group_items(items, group_by)
        
        # 对每个分组计算统计信息
        group_stats = {}
        for group_key, group_items in grouped_items.items():
            # 项目数量
            group_stats[group_key] = {
                "count": len(group_items),
                "percentage": len(group_items) / len(items) * 100 if items else 0
            }
            
            # 如果有数值字段，计算统计信息
            if group_items and "value" in group_items[0]:
                values = [item.get("value", 0) for item in group_items]
                group_stats[group_key].update(calculate_statistics(values))
        
        return {
            **summary,
            "group_by": group_by,
            "groups": group_stats,
            "details": grouped_items
        }
    
    def generate_trend_report(self, items: List[Dict[str, Any]], time_field: str, interval: str = "day") -> Dict[str, Any]:
        """
        生成趋势报告
        
        Args:
            items: 项目列表
            time_field: 时间字段名
            interval: 时间间隔（day, week, month）
            
        Returns:
            趋势报告
        """
        if not items:
            return {"count": 0, "message": "No data available"}
        
        # 确保所有项目都有时间字段
        valid_items = [item for item in items if time_field in item and item[time_field]]
        
        if not valid_items:
            return {"count": 0, "message": f"No items with valid {time_field} field"}
        
        # 将时间戳转换为datetime对象
        for item in valid_items:
            if isinstance(item[time_field], (int, float)):
                item["_datetime"] = datetime.fromtimestamp(item[time_field])
            else:
                try:
                    item["_datetime"] = datetime.fromisoformat(item[time_field].replace("Z", "+00:00"))
                except (ValueError, AttributeError):
                    # 如果无法解析，跳过此项
                    item["_datetime"] = None
        
        # 过滤掉无法解析时间的项目
        valid_items = [item for item in valid_items if item["_datetime"] is not None]
        
        # 按时间间隔分组
        time_groups = {}
        
        for item in valid_items:
            dt = item["_datetime"]
            
            if interval == "day":
                group_key = dt.strftime("%Y-%m-%d")
            elif interval == "week":
                # 使用ISO周格式（周一为一周的开始）
                group_key = f"{dt.isocalendar()[0]}-W{dt.isocalendar()[1]:02d}"
            elif interval == "month":
                group_key = dt.strftime("%Y-%m")
            else:
                # 默认按天分组
                group_key = dt.strftime("%Y-%m-%d")
            
            if group_key not in time_groups:
                time_groups[group_key] = []
            
            time_groups[group_key].append(item)
        
        # 计算每个时间组的统计信息
        trend_data = {}
        for group_key, group_items in sorted(time_groups.items()):
            trend_data[group_key] = {
                "count": len(group_items)
            }
            
            # 如果有数值字段，计算统计信息
            if "value" in valid_items[0]:
                values = [item.get("value", 0) for item in group_items]
                trend_data[group_key].update(calculate_statistics(values))
        
        return {
            "count": len(valid_items),
            "interval": interval,
            "time_field": time_field,
            "trend": trend_data
        }
    
    def save_report(self, report: Dict[str, Any], file_path: str, format: str = "json") -> bool:
        """
        保存报告到文件
        
        Args:
            report: 报告数据
            file_path: 文件路径
            format: 文件格式（json或csv）
            
        Returns:
            是否成功
        """
        if format.lower() == "json":
            return self.data_processor.export_to_json(report, file_path)
        elif format.lower() == "csv":
            # 对于CSV，我们只能导出扁平结构
            if "details" in report and isinstance(report["details"], list):
                return self.data_processor.export_to_csv(report["details"], file_path)
            else:
                logger.error("CSV格式只支持扁平的数据结构")
                return False
        else:
            logger.error(f"不支持的格式: {format}")
            return False